<template>
  <div style="width: 100%; height: 100%; position: relative">
    <div
      :class="className"
      :style="{ height: height, width: width, 'z-index': 2 }"
      v-loading="loading"
    />
    <!-- 下角标 -->
    <!-- <span
      v-for="(item, i) in xAxisLabelActives"
      :key="i"
      class="xAxis-active-icon"
      :style="{
        position: 'absolute',
        left: `${item.offsetX}px`,
        bottom: '0px',
      }"
    ></span> -->
  </div>
</template>

<script>
import resize from "./mixins/resize";
import variables from "@/assets/styles/element-variables.scss";
const xAxisLabelActiveColor = variables.theme; //x轴坐标label选中颜色
const xAxisLabelDefaultColor = "#7D8292"; //x轴坐标label默认颜色

export default {
  mixins: [resize],
  props: {
    className: {
      type: String,
      default: "chart",
    },
    width: {
      type: String,
      default: "100%",
    },
    height: {
      type: String,
      default: "100%",
    },
    option: {
      type: Object,
      default: () => {},
      required: true,
    },
    // 点击事件，可以点击的项
    enableClickOptions: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      chart: null,
      loading: true,
      xAxisLabelActives: [], // 横坐标选中的对象
      currentDatazoom: null, //当前缩放大小及位置
    };
  },
  watch: {
    option: {
      deep: true,
      immediate: true,
      handler(val) {
        if (val) {
          this.initChart();
        }
      },
    },
  },
  mounted() {
    this.initChart();
  },
  beforeDestroy() {
    if (!this.chart) {
      return;
    }
    this.chart.off("click");
    this.chart.dispose();
    this.chart = null;
  },
  methods: {
    initChart() {
      if (!this.$el) {
        return;
      }

      const el = this.$el.getElementsByClassName(this.className)[0];
      if (!el) {
        return;
      }

      if (!this.chart) {
        this.chart = this.$echarts.init(el);

        this.initEvent();
      }

      this.setOptions();
    },
    initEvent() {
      if (!this.enableClickOptions?.length) {
        return;
      }

      this.chart.off("click");

      this.enableClickOptions.forEach((op) => {
        this.chart.on("click", op, (e) => {
          const fnName = op.replace(".", "");
          const eventName = op.replace(".", "-");
          if (this[`handle${fnName}Click`]) {
            this[`handle${fnName}Click`](eventName, e);
          }
          this.$emit(`${eventName}-click`, e);
        });
      });

      // 有缩放组件时，监听滚动事件
      if (this.option.dataZoom?.length > 0) {
        this.chart.on("datazoom", (e) => {
          if (e.batch?.length) {
            this.currentDatazoom = {
              start: e.batch[0].start,
              end: e.batch[0].end,
            };
          } else {
            this.currentDatazoom = {
              start: e.start,
              end: e.end,
            };
          }
        });
      }
    },
    // 参数：resetDataZoom：是否重新设置dataZoom，为false则定位到上一次的位置
    setOptions({ resetDataZoom } = { resetDataZoom: true }) {
      let option = {
        color: [
          "#5470c6",
          "#91cc75",
          "#fac858",
          "#ee6666",
          "#73c0de",
          "#3ba272",
          "#fc8452",
          "#9a60b4",
          "#ea7ccc",
        ],
        ...this.option,
      };

      this.chart.setOption(option);

      if (!resetDataZoom && this.currentDatazoom) {
        // 若被移动过，则更新数据时，定位到上一次移动的位置
        this.chart.dispatchAction({
          type: "dataZoom",
          start: this.currentDatazoom.start,
          end: this.currentDatazoom.end,
        });
      } else {
        // 重置位置
        this.currentDatazoom = null;
      }

      this.loading = false;
    },
    handlexAxiscategoryClick(eventName, e) {
      // 是否已选中
      const existIndex = this.xAxisLabelActives.findIndex(
        (ele) => ele.value == e.value
      );

      const index = this.option.xAxis.data.findIndex(
        (ele) => ele.value == e.value
      );

      // 修改选中状态的样式
      let dataValue = this.option.xAxis.data[index];
      if (existIndex != -1) {
        // 标签label样式设置
        if (typeof dataValue == "string") {
          this.option.xAxis.data[index] = dataValue.replace(
            /(^{active\|)|(}$)/g,
            ""
          );
        } else {
          this.option.xAxis.data[index].textStyle = {
            color: xAxisLabelDefaultColor,
            fontWeight: "normal",
          };
        }

        // 记录选中结果
        this.xAxisLabelActives.splice(existIndex, 1);

        this.$emit(`${eventName}-unselect`, this.xAxisLabelActives);
      } else {
        // 标签label样式设置
        if (typeof dataValue == "string") {
          this.option.xAxis.data[index] = `{active|${dataValue}}`;
        } else {
          this.option.xAxis.data[index].textStyle = {
            color: xAxisLabelActiveColor,
            fontWeight: "600",
          };
        }

        // 下标三角标志位置
        const offsetX = this.chart.convertToPixel({ xAxisIndex: 0 }, index);

        // 记录选中结果
        this.xAxisLabelActives.push({
          ...this.option.xAxis.data[index],
          offsetX,
        });

        this.$emit(`${eventName}-selected`, this.xAxisLabelActives);
      }

      // 滚动条定位到上一次的位置
      this.setOptions({ resetDataZoom: false });
    },
    handleserieslineClick(eventName, e) {
      if (e.componentType != "series") {
        return;
      }
      this.$emit(`${eventName}-selected`, e);
    },
  },
};
</script>
<style lang="scss" scoped>
@import "../../../../assets/styles/element-variables";
.xAxis-active-icon {
  width: 0;
  height: 0;
  border-top: 8px solid transparent;
  border-left: 8px solid transparent;
  border-right: 8px solid transparent;
  border-bottom: 8px solid $--color-primary;
  border-radius: 3px;
  transform: translate(-50%, -50%);
  z-index: 1;
}
</style>
